<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测仪器管理
 */

namespace app\admin\service;

use app\common\model\InstrumentModel;

class InstrumentService
{
    protected static $model;

    /**
     * InstrumentService constructor.
     * @param InstrumentModel $instrumentModel
     * @author zws
     */

    public function __construct(InstrumentModel $instrumentModel)
    {
        self::$model = $instrumentModel;
    }

    /**
     * 检测仪器列表
     * @param $param
     * @return array|\PDOStatement|string|\think\Collection
     * @author zws
     */
    public function index($param)
    {
        if (!isset($param['page']) || empty($param['page'])) {
            $param['page'] = 1;
        }
        if (!isset($param['limit']) || empty($param['limit'])) {
            $param['limit'] = 10;
        }
        $where = [['is_del', '=', 1]];

        if (!empty($param['type'])) {
            $where = array_merge($where, [['type', '=', $param['type']]]);
        }

        if (!empty($param['instrument_num'])) {
            $where = array_merge([['instrument_num', 'like', "%".$param['instrument_num']."%"]]);
        }

        // 获取总数
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => $count];
        }
        // 查询检测人员列表
        $result = self::$model->where($where)
            ->page($param['page'], $param['limit'])
            ->order('id', 'asc')
            ->select()->toArray();
        return ['data' => $result, 'count' => $count];
    }

    /**
     * 获取单个仪器数据
     * @param $param
     * @return array|null|\PDOStatement|string|\think\Model
     * @author zws
     */
    public function edit($param)
    {
        if (empty($param) || !isset($param['id']) || empty($param['id'])) {
            app_fail(9997);//参数错误
        }
        $row = self::$model->where('id', '=', $param['id'])->find();
        if (!$row) {
            app_fail(7999);
        }
        return $row;

    }

    /**
     * 检测仪器添加、修改
     * @param $param
     * @return bool
     * @author zws
     */
    public function update($param)
    {
        if (empty($param)) {
            app_fail(9997);//参数错误
        }

        try{
            $where = !empty($param['id']) ? ['id'=>$param['id']] : [];
            $result = self::$model->allowField(true)->save($param, $where);
            return $result;
        } catch (Exception $e) {
            app_fail(9899);//仪器编辑失败
        }
    }
}